<?php

namespace App\Http\Controllers\Admin;

use App\Models\Agent;
use App\Models\Dictionary;
use App\Models\Order;
use App\Models\OrderLog;
use App\Models\OrderRecord;
use App\Models\Product;
use App\Traits\ExcelTrait;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;


class OrderController extends BaseController
{
    use ExcelTrait;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $customer = $request->input('customer','');
        $phone = $request->input('phone','');
        $category_id_first = $request->input('category_id_first','');
        $category_id_second = $request->input('category_id_second','');
        $agent_id = $request->input('agent_id','');
        $product_name = $request->input('product_name','');
        $create_time_start = $request->input('create_time_start','');
        $create_time_end = $request->input('create_time_end','');
        $my_company = $request->input('my_company','');
        $manager = $request->input('manager','');
        $parent_company = $request->input('parent_company','');
        $parent_manager = $request->input('parent_manager','');
        $status = $request->input('status','');

        $query = Order::select();
        if($customer!=''){
            $query=$query->where('userinfo->customer','like',"%$customer%");
        }
        if($phone!=''){
            $query=$query->where('userinfo->phone','=',$phone);
        }
        if($category_id_first!=''){
            $query=$query->where('confirm_loan->category_id_first','=',$category_id_first);
        }
        if($category_id_second!=''){
            $query=$query->where('confirm_loan->category_id_second','=',$category_id_second);
        }
        if($agent_id!=''){
            $query=$query->where('confirm_loan->agent_id','=',$agent_id);
        }
        if($product_name!=''){

            $query=$query->where('confirm_loan->product_name','like',"%$product_name%");
        }
        if($create_time_start!=''){
            $query=$query->where('created_at','>=',$create_time_start);
        }
        if($create_time_end!=''){
            $query=$query->where('created_at','<=',$create_time_end);
        }
        if($create_time_end!='' && $create_time_start!=''){
            if($create_time_start>$create_time_end){
                die('<script>alert("申请时间前值不能比后值大");history.back();</script>');
            }
            $query=$query->where('created_at','<=',$create_time_end)->where('created_at','>=',$create_time_start);
        }
        if($my_company!=''){
            $query=$query->where('channel_info->my_company','like',"%$my_company%");
        }
        if($manager!=''){
            $query=$query->where('channel_info->manager','like',"%$manager%");
        }
        if($parent_company!=''){
            $query=$query->where('channel_info->parent_company','like',"%$parent_company%");
        }
        if($parent_manager!=''){
            $query=$query->where('channel_info->parent_manager','like',"%$parent_manager%");
        }
        if($status!=''){
            $query=$query->where('status','=',"$status");
        }
        $orders = $query->orderBy('created_at','desc')->paginate(10);

        $orders->appends(['customer'=>$customer,'phone'=>$phone,'category_id_first'=>$category_id_first,'category_id_second'=>$category_id_second,'agent_id'=>$agent_id,'product_id'=>$product_name,'create_time_start'=>$create_time_start,'create_time_end'=>$create_time_end,'my_company'=>$my_company,'manager'=>$manager,'parent_company'=>$parent_company,'parent_manager'=>$parent_manager,'status'=>$status]);
        $orders->customer=$customer;
        $orders->phone=$phone;
        $orders->category_id_first=$category_id_first;
        $orders->category_id_second=$category_id_second;
        $orders->agent_id=$agent_id;
        $orders->product_name=$product_name;
        $orders->create_time_start=$create_time_start;
        $orders->create_time_end=$create_time_end;
        $orders->my_company=$my_company;
        $orders->manager=$manager;
        $orders->parent_company=$parent_company;
        $orders->parent_manager=$parent_manager;
        $orders->status=$status;
        $categories=Dictionary::select('id','name')->where(['pid'=>1])->get();
        $second_categories=Dictionary::where(['pid'=>$orders->category_id_first])->get();
        $agents=Agent::select('id','name')->get();
//        dump($orders->toArray());
        return view('Admin.Order.index',compact('orders','categories','second_categories','agents'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        $order = Order::findOrFail($id);
        return view('Admin.Order.show',compact('order'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $order = Order::findOrFail($id);

        if(array_key_exists('category_id_first',$order->confirm_loan)) {
            $second_categories = Dictionary::where(['pid' => $order->confirm_loan['category_id_first']])->get();
        }else{
            $second_categories = [];
        }

        $agents = Agent::select('id','name')->get();
        if(isset($order->confirm_loan['product_id'])){
            $product_one = Product::findOrFail($order->confirm_loan['product_id']);
        }
        $products = Product::select('id','name')->get();


        $categories = Dictionary::select('id','name')->where(['pid'=>1])->get();

        return view('Admin.Order.edit',compact('order','categories','second_categories','agents','products','product_one'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
//        dd($request->all());
        $session = Session::all();
        $user  = $session['admin'];
        $logids = OrderLog::where(['order_id'=>$id])->get();
        $logCount = count($logids);
        if($request->fangkuan == 0){
            //退单
            $validator = Validator::make($request->all(),[
                'customer'=>'required',
                'phone'=>'required',
                'idcard'=>'required',
                'reason'=>'required'
            ]);
            if(!$validator->fails()){
                $order  =  Order::findOrFail($id);

                if($order){
                    $customer = $request->customer ? $request->customer : $order->userinfo['customer'];
                    $phone = $request->phone ? $request->phone :$order->userinfo['phone'];
                    $idcard = $request->idcard ? $request->idcard : $order->userinfo['idcard'];
                    $reason = $request->reason ? $request->reason : $order->reason;
                    $confirm = ['admin_id'=>$user['id'],'time'=>date('Y-m-d H:i:s')];
                    DB::beginTransaction();
                    try{
                        $update = Order::where(['id'=>$id])
                            ->update(['userinfo->customer'=>$customer,'userinfo->phone'=>$phone,'userinfo->idcard'=>$idcard,'reason'=>$reason,'status'=>'-1','confirm_loan'=>json_encode($confirm)]);
                        if($logCount){
                            $this->insertLog('4', $id ,$user);
                        }else{
                            $this->insertLog('3', $id ,$user);
                        }

                        DB::commit();
                        return $this->ajaxResponse();
                    }
                    catch (\Exception $e){
                        DB::rollback();//事务回滚
                        $this->set('code',1);
                        $this->set('message','修改失败');
                        return $this->ajaxResponse();
                    }
                }
            }

        }else{
            //放款 或者 修改资料
            $validator = Validator::make($request->all(),[
                'customer'=>'required',
                'phone'=>'required',
                'idcard'=>'required',
                'category_id_first'=>'required',
                'agent_id'=>'required',
                'product_id'=>'required',
                'loan_amount'=>'required',
                'fee_type'=>'required',
                'fee_value'=>'required',
            ]);
            if(!$validator->fails()){
                $order  =  Order::findOrFail($id);
                if($order){
                    $customer = $request->customer ? $request->customer : $order->userinfo['customer'];
                    $phone = $request->phone ? $request->phone :$order->userinfo['phone'];
                    $idcard = $request->idcard ? $request->idcard : $order->userinfo['idcard'];
                    if($order->confirm)
                    {
                        $agent_id = $request->agent_id ? $request->agent_id : $order->confirm_loan['agent_id'];
                        $product_id = $request->product_id ? $request->product_id : $order->confirm_loan['product_id'];
                        $product = Product::find($product_id);
                        $product_name = $product ? $product->name : '';
                        $loan_amount = $request->loan_amount ? $request->loan_amount : $order->confirm_loan['loan_amount'];
                        $fee_type = $request->fee_type ? $request->fee_type : $order->confirm_loan['fee_type'];
                        $fee_value = $request->fee_value ? $request->fee_value : $order->confirm_loan['fee_value'];
                        $category_id_first = $request->category_id_first ? $request->category_id_first : $order->confirm_loan['category_id_first'];
                        $category_id_second = $request->category_id_second ? $request->category_id_second : $order->confirm_loan['category_id_second'];
                        $confirm = ['loan_amount' => $loan_amount, 'fee_type' => $fee_type, 'fee_value' => $fee_value, 'category_id_second' => $category_id_second, 'category_id_first' =>$category_id_first,'agent_id'=>$agent_id,'product_id'=>$product_id,'product_name'=>$product_name,'admin_id'=>$user['id'],'time'=>date('Y-m-d H:i:s')];

                    }else {
                        $agent_id = $request->agent_id;
                        $product_id = $request->product_id;
                        $product = Product::find($product_id);
                        $product_name = $product ? $product->name : '';
                        $confirm = ['loan_amount' => $request->loan_amount, 'fee_type' => $request->fee_type, 'fee_value' => $request->fee_value, 'category_id_second' => $request->category_id_second, 'category_id_first' => $request->category_id_first,'agent_id'=>$agent_id,'product_id'=>$product_id,'product_name'=>$product_name,'admin_id'=>$user['id'],'time'=>date('Y-m-d H:i:s')];
                    }
                    if($request->customer != $order->userinfo['customer'] || $request->phone !=$order->userinfo['phone'] || $request->idcard !=$order->userinfo['idcard']){
                        //修改资料
                        DB::beginTransaction();
                        try {
                            $update = Order::where(['id' => $id])
                                ->update(['userinfo->customer' => $customer, 'userinfo->phone' => $phone, 'userinfo->idcard' => $idcard,  'confirm_loan->agent_id' => $agent_id, 'confirm_loan->product_id' => $product_id,  'confirm_loan'=>json_encode($confirm)]);
                            //写入日志
                            $res = $this->insertLog('2', $id, $user);
                            DB::commit();
                            return $this->ajaxResponse();
                        }
                        catch (\Exception $e){
                            DB::rollback();//事务回滚
                            $this->set('code',1);
                            $this->set('message','修改失败');
                            return $this->ajaxResponse();
                        }
                    }
                    else{
                        //放款
                        DB::beginTransaction();
                        try {
                            $update = Order::where(['id' => $id])
                                ->update(['userinfo->customer' => $customer, 'userinfo->phone' => $phone, 'userinfo->idcard' => $idcard,  'confirm_loan->agent_id' => $agent_id, 'confirm_loan->product_id' => $product_id, 'confirm_loan'=>json_encode($confirm), 'status' => '1','reason'=>'']);
                            Product::where(['id'=>$product_id])->increment('apply_num',1);
                            //写入日志
                            if($logCount){
                                $this->insertLog('4', $id ,$user);
                            }else{
                                $this->insertLog('3', $id ,$user);
                            }
                            $orderRecord = OrderRecord::where(['product_id' => $product_id, 'order_id' => $id])->first();
                            if ($orderRecord == null) {
                                OrderRecord::create(['product_id' => $product_id, 'order_id' => $id]);
                            }
                            DB::commit();
                            return $this->ajaxResponse();
                        }
                        catch (\Exception $e){
                            DB::rollback();//事务回滚
                            $this->set('code',2);
                            $this->set('message','修改失败');
                            return $this->ajaxResponse();
                        }

                    }

                }
            }
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * 查看签单日志
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function orderLogs($id)
    {
        $orderLog = OrderLog::where(['order_id'=>$id])->get();

        return view('Admin.Order.log',compact('orderLog'));
    }



    /**
     * 写入日志
     * @param $value
     * @param $order_id
     * @param array $user
     * @return bool
     */
    public function insertLog($value, $order_id, $user=[])
    {
        $result= OrderLog::create(['name'=>$user['username'],'operate_type'=>$value,'operator_id'=>$user['id'],'order_id'=>$order_id]);
        if($result){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 订单导出
     */
    public function orderExport(Request $request){
        if($request->ids == 'all') {
            $title = '签单记录-' . date('YmdHis', time());
            $order = new Order();
            $data = $order->getExportData('all');
        }else{
            $ids = trim($request->ids, ',');
            $title = '签单记录-' . date('YmdHis', time());
            $order = new Order();
            $data = $order->getExportData('select',$ids);
        }
        $this->excelExport($title, $data);
    }
}
